<template>
  <basic-dialog
    :showFooter="false"
    :width="'80%'"
    :visible.sync="exportVisible"
    :title="'批量维护存量信息'"
    :handle-close="handleCloseDialog"
  >
    <el-card class="search-card" shadow="never">
      <BasicForm
        ref="formData"
        :isScalingBtn="false"
        formItemWidth="75px"
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card" shadow="never">
      <basic-table
        showActionCol
        showPagination
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        :showSelectCol="false"
        :actionColWidth="200"
        :actionRender="actionRender"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-upload
            class="upload-temp"
            :action="actionUrl"
            accept=".xls, .xlsx"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :data="{ batchType: 'cpfrStockManager', operateTypeByCode: 'templateData' }"
          >
            <el-button
              size="mini"
              type="primary"
              :loading="importLoading"
              @click="handleImport"
              >导入</el-button
            >
          </el-upload>
        </div>
      </basic-table>
    </el-card>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/skusTable';
import skusPage from '@/mixins/commodity/skusPage';
import { BATCH_FORM_ITEM_LIST, BATCH_TABLE_COLUMNS } from '../constants';
import {
  queryUploadStockListService,
  queryDownloadUrlService
} from '@api/stock/stockOverflow'
import { setAuthBtnId } from '@/utils/bizUtils';

export default {
  mixins: [skusPage],
  components: {
    BasicDialog,
    BasicForm,
    BasicTable
  },
  props: {
    exportVisible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      importLoading: false,
      formItemList: BATCH_FORM_ITEM_LIST, // 表单列集合
      tableInfo: {
        list: [], // 表格数据
        columns: BATCH_TABLE_COLUMNS, // 表格columns
        loading: false // 表格加载loading
      },
      pageSizes: [100, 500, 1000], // 每页条数size集合
      formData: {
        batchNo: '',
        departmentName: '',
        createdAt: [],
        createdUserName: '',
      },
      actionUrl: '',
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 100 // 当前页码size
      },
    };
  },
  methods: {
    actionRender (h, { row }) {
      return (
        <div class="table-action">
          <el-button size="mini" type="text" onClick={() => this.handleExportNormalData(row)}>下载正常文件</el-button>
          <el-button size="mini" type="text" onClick={() => this.handleExportAbnormalData(row)}>下载异常文件</el-button>
        </div>
      );
    },
    handleImport () {
      setAuthBtnId('导入')
      const { menuId, buttonId } = sessionStorage;
      this.actionUrl = `${this.uploadBaseURL}dataBatch/purchasePrice/file/upload?menuId=${menuId}&buttonId=${buttonId}`
    },
    // 导出正常数据
    handleExportNormalData (row) {
      this.exportFileService('outputOutputData', row);
    },
    // 导出异常数据
    handleExportAbnormalData (row) {
      this.exportFileService('outputValidErrorData', row);
    },
    async getTableData () {
      const [startCreatedAt = '', endCreatedAt = ''] = this.formData.createdAt || []
      const param = {
        data: {
          batchType: 5,
          ...this.formData,
          startCreatedAt,
          endCreatedAt,
        },
        ...this.pagination,
      }
      const res = await queryUploadStockListService(param, state => { this.tableInfo.loading = state })
      if (res?.retData) {
        const { records, total } = res.retData
        this.tableInfo.list = records;
        this.total = total;
      }
    },
    // 导出文件
    async exportFileService (type, row) {
      const param = {
        type,
        batchNo: row.batchNo
      }
      const res = await queryDownloadUrlService(param, state => { this.tableInfo.loading = state })
      if (res.retData && res.retData.downloadUrl) {
        window.location.href = res.retData.downloadUrl;
      }
    },
    // 关闭弹窗
    handleCloseDialog () {
      this.$emit('update:exportVisible', false);
    },
    beforeUpload () {
      this.importLoading = true;
    },
    uploadSuccess (res) {
      this.importLoading = false;
      const { retStatus, retMessage } = res
      if (retStatus == 1) {
        this.$message.success(retMessage)
        this.getTableData()
      } else {
        this.$message.error(retMessage)
      }
    },
    uploadError () {
      this.importLoading = false;
      this.$message.error('导入异常')
    },
  }
};
</script>
<style scoped>
.el-select, .el-date-editor.el-input {
  width: 100%;
}
.search-card {
  margin-bottom: 10px;
}
</style>
